#!/bin/bash

# 对proot不起作用，只能在启动时加 -k 参数来指定hostname!
# echo "droidvm" >     /etc/hostname
# export HOSTNAME=`cat /etc/hostname`
# hostname $HOSTNAME

function mkscripts() {
	cat <<- EOF > /exbin/vm_gen_dns_cache.sh
		#!/system/bin/sh

		# 测试 2025.03.31
		exit 0

		currdir=\`pwd\`
		export PATH=\${currdir}/tools:\$PATH

        hostname2cache=""
        if [ \$# -ge 1 ]; then
			hostname2cache+=" \$@"
        else
 			echo ""         > ${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${USER_DNS_CACHE}
			echo "# 生成的" >>${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${USER_DNS_CACHE}

			hostname2cache+=" ${GITHUB_PROXY_HOST}"
			hostname2cache+=" playwright.azureedge.net"
			hostname2cache+=" home-store-packages.uniontech.com"
			hostname2cache+=" droidvmres-1316343437.cos.ap-shanghai.myqcloud.com"
			hostname2cache+=" gitee.com"
			hostname2cache+=" foruda.gitee.com"
			hostname2cache+=" mirrors.bfsu.edu.cn"
			hostname2cache+=" mirrors.ustc.edu.cn"
			hostname2cache+=" mirrors.tuna.tsinghua.edu.cn"
			hostname2cache+=" mirror.tuna.tsinghua.edu.cn"
			hostname2cache+=" security.debian.org"
			hostname2cache+=" deb.debian.org"
			hostname2cache+=" pypi.tuna.tsinghua.edu.cn"
			hostname2cache+=" mirrors.aliyun.com"
			hostname2cache+=" mirrors.cloud.tencent.com"
			hostname2cache+=" pypi.tuna.tsinghua.edu.cn"
			hostname2cache+=" archive.ubuntu.com"
			hostname2cache+=" ports.ubuntu.com"
			hostname2cache+=" security.ubuntu.com"
        fi
        # echo \$hostname2cache

        DNS_SERVER_LIST=\`cat ${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}/etc/resolv.conf |grep nameserver|cut -c 12-\`
        # echo \$DNS_SERVER_LIST

        function zz_gethostbyname() {
			DOMAIN_NAME=\$1
            OK2GET=0

            for DOMAIN_SERVER in \$DNS_SERVER_LIST
            do
                # echo \$DOMAIN_SERVER
                tmpres=\`${ALINKER64} \${app_home}/tools/busybox/busybox nslookup \${DOMAIN_NAME} \$DOMAIN_SERVER\`
                OK2GET=\$?
                if [ \$OK2GET -eq 0 ]; then
                    break
                fi
            done

            if [ \$OK2GET -ne 0 ]; then
                return \$OK2GET
            fi
            echo "\$tmpres"|tail -n +4|grep Address| \\
            awk -v FS=": " -v OFS="" -v header="" -v tail=" \${DOMAIN_NAME}" '{print header,\$2,tail}' \\
            >>${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${USER_DNS_CACHE}
        }

        for hostname in \$hostname2cache
        do
            echo "正在解析：\$hostname"
            zz_gethostbyname \$hostname
            if [ \$? -ne 0 ]; then
                echo "解析失败：\$hostname"
                # rm -rf ${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${USER_DNS_CACHE}
                # exit 1
            fi
        done
	    chmod 666 ${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${USER_DNS_CACHE}

	EOF
	chmod a+x /exbin/vm_gen_dns_cache.sh

	cat <<- EOF > /exbin/vm_getHostByName.sh
		#!/system/bin/sh

		# 测试 2025.03.31
		exit 0

		currdir=\`pwd\`
		export PATH=\${currdir}/tools:\$PATH

        hostname2cache=""
        if [ \$# -ge 1 ]; then
			hostname2cache+=" \$@"
        else
            exit 1
        fi
        # echo \$hostname2cache

        DNS_SERVER_LIST=\`cat ${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}/etc/resolv.conf |grep nameserver|cut -c 12-\`
        # echo \$DNS_SERVER_LIST

        function zz_gethostbyname() {
			DOMAIN_NAME=\$1
            OK2GET=0

            for DOMAIN_SERVER in \$DNS_SERVER_LIST
            do
                # echo \$DOMAIN_SERVER
                tmpres=\`${ALINKER64} \${app_home}/tools/busybox/busybox nslookup \${DOMAIN_NAME} \$DOMAIN_SERVER\`
                OK2GET=\$?
                if [ \$OK2GET -eq 0 ]; then
                    break
                fi
            done

            if [ \$OK2GET -ne 0 ]; then
                return \$OK2GET
            fi
            echo "\$tmpres"|tail -n +4|grep Address| \\
            awk -v FS=": " -v OFS="" -v header="" -v tail=" \${DOMAIN_NAME}" '{print header,\$2,tail}'
        }

        for hostname in \$hostname2cache
        do
            # echo "正在解析：\$hostname"
            zz_gethostbyname \$hostname
            if [ \$? -ne 0 ]; then
                exit 1
            fi
        done
        exit
	EOF
	chmod a+x /exbin/vm_getHostByName.sh
}

function apply_default_nameserver() {
	# /exbin/ipc/AndroidDnsServerList.txt 这个文件，安卓网络有变动时都会自动重新生成
    rm -rf /etc/resolv.conf
    rm -rf /etc/resolv.conf.force
	(cd /etc && ln -sf /exbin/ipc/AndroidDnsServerList.txt /etc/resolv.conf)
}

echo '正在配置虚拟系统中的 DNS 服务器列表 ...'

if [ -f   /etc/resolv.conf.force ]; then
    # 如果文件是指向 /exbin/ipc/AndroidDnsServerList.txt 的链接，必须先手动删除，否则下面的复制动作会覆盖 /exbin/ipc/AndroidDnsServerList.txt
    rm -rf /etc/resolv.conf
	cp -f  /etc/resolv.conf.force  /etc/resolv.conf
else
	apply_default_nameserver
fi


# 必须的静态解析地址(127.0.0.1)
cat <<- EOF > /etc/hosts
	# IPv4.
	127.0.0.1   localhost.localdomain localhost droidvm

	# IPv6.
	::1         localhost.localdomain localhost ip6-localhost ip6-loopback
	fe00::0     ip6-localnet
	ff00::0     ip6-mcastprefix
	ff02::1     ip6-allnodes
	ff02::2     ip6-allrouters
	ff02::3     ip6-allhosts
EOF


USER_DNS_CACHE=/etc/hosts.user
mkscripts

if [ "$PRE_RESOLV_DNS_ADDRESS" != "" ]; then
	# rm -rf ${USER_DNS_CACHE}
	if [ ! -f ${USER_DNS_CACHE} ]; then

		echo "正在安卓端生成dns缓存"
		cd /exbin && droidexec ./vm_gen_dns_cache.sh

	fi # endof /etc/hosts.user

	if [ -f ${USER_DNS_CACHE} ]; then
		cat ${USER_DNS_CACHE} >> /etc/hosts
	fi
fi


# 手动解析测试
# ==========================================
# dig droidvm.com
# nslookup droidvm.com
# nslookup droidvm.com 192.168.1.1 # 连接指定的DNS服务器: 192.168.1.1
# nslookup - 192.168.1.1           # 连接指定的DNS服务器: 192.168.1.1，交互模式
# strace -c ping -c 2 -n droidvm.com
# strace ping -c1 droidvm.com
# libc-bin: /usr/bin/getent => getent hosts droidvm.com
# python -c "import socket; print(socket.gethostbyname('example.com'))"
# busybox nslookup bing.com 192.168.1.1     # 这个可能最实用
# busybox nslookup mirrors.tuna.tsinghua.edu.cn 192.168.1.1|tail -n -2
# ip route list table 0|grep default|grep via|awk '{print "nameserver "$3}'
# resolvconf

# wget -q -O - myip.ipip.net					# 安卓端查询公网ip
# curl      myip.ipip.net						# 查询公网ip
# https://www.test-ipv6.com/index.html.zh_CN	# 查询是否支持 ipv6
